package com.tang.mybatis.session;

import com.tang.mybatis.constants.Constants;
import com.tang.mybatis.session.defaults.DefaultSqlSessionFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;

/**
 * @author Tang
 * @classname SqlSessionFactoryBuilder
 * @description [ 构建 SqlSessionFactory ]
 * @date 2022/4/6 15:57
 */
public class SqlSessionFactoryBuilder {

    public SqlSessionFactory build(String fileName) {
        InputStream inputStream = ClassLoader.getSystemResourceAsStream(fileName);
        return build(inputStream);
    }

    public SqlSessionFactory build(InputStream inputStream) {

        try {
            Configuration.properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Configuration configuration = new Configuration();

        // 简单解析xml文件
        try {
            loadMapperInfo(Configuration.getProperty(Constants.MAPPER_LOCATION).replaceAll("\\.", "/"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new DefaultSqlSessionFactory(configuration);
    }

    private void loadMapperInfo(String fileName) throws Exception {
        URL url = ClassLoader.getSystemResource(fileName);
        File file = new File(url.getFile());
        File[] listFiles = file.listFiles((f) -> {
            return true;
        });
        if (Objects.nonNull(listFiles)) {
            for (File itemFile : listFiles) {
                if (file.isDirectory()) {
                    loadMapperInfo(fileName + "/" + itemFile.getName());
                }
            }
        } else if (file.isFile() && file.getName().endsWith(Constants.MAPPER_FILE_SUFFIX)) {

        }
    }
}